package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @version 1.0
 * @auther gwt
 * @date 2021/6/24 16:29
 */
@RestController
@RequestMapping("/login")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String  validateCodeInRedis= jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if(!StringUtils.equals(validateCode,validateCodeInRedis)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Member member=memberService.findByTelephone(telephone);
        if(member==null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);


            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 300, json);
        }
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(60 * 60 * 24 * 30);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
